package com.willow.liutige.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 线程池配置
 */
@Configuration
@EnableAsync
public class ThreadPoolConfig implements AsyncConfigurer {

    /**
     * 项目共用线程池
     */
    public static final String liutige_EXECUTOR = "liutigeExecutor";

    @Override
    public Executor getAsyncExecutor() {
        return liutigeExecutor();
    }

    // I/O 密集型线程池
    @Bean(liutige_EXECUTOR)
    public ThreadPoolTaskExecutor liutigeExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setWaitForTasksToCompleteOnShutdown(true); // 关闭时等待所有任务都完成,优雅停机的关键
        executor.setCorePoolSize(20);
        executor.setMaxPoolSize(50);
        executor.setKeepAliveSeconds(60);
        executor.setQueueCapacity(1000);
        executor.setThreadNamePrefix("liutige-executor-");
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); // 拒绝策略：由调用线程处理任务
        executor.initialize();
        return executor;
    }
}
